import datetime

import jqdatasdk
from django.core.management.base import BaseCommand
from stocksys import models as stocksys_models


class Command(BaseCommand):
    help = 'create_fund_data_from_jqdata'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('清空基金数据'))
        stocksys_models.Fund.objects.all().delete()
        self.stdout.write(self.style.SUCCESS('验证远程数据密钥'))
        auth_key = None
        with open("data/auth_key.key") as key:
            auth_key = key.read().split(",")
            jqdatasdk.auth(auth_key[0], auth_key[1])
            print(auth_key)
        self.stdout.write(self.style.SUCCESS('请求远程数据'))
        data = jqdatasdk.get_all_securities(['fund'])
        # data.to_csv("../data/fund_code.csv")
        self.stdout.write(self.style.SUCCESS('初始化数据'))
        data['code'] = data.index
        data.index = [x for x in range(len(data))]
        # data['exchange_abbreviated_name'] = data['fund_code'].map(lambda x: x.split('.')[1])
        data['fund_code'] = data['code'].map(lambda x: x.split('.')[0])
        data['jqdata_abbreviated'] = data['code'].map(lambda x: x.split('.')[1])

        data['abbreviated_name'] = data['name']
        data = data.drop('name', axis=1)
        data['fund_name'] = data['display_name']
        data = data.drop('display_name', axis=1)
        data['last_update_time'] = datetime.datetime.now().strftime("%Y-%m-%d")
        data = data[
            ['fund_name', 'abbreviated_name', 'fund_code', 'last_update_time',
             'start_date', 'end_date', 'type','jqdata_abbreviated']]
        print(data)
        self.stdout.write(self.style.SUCCESS('载入基金代码数据'))
        for index in range(len(data)):
            row = data.loc[index].to_dict()
            # 股票交易所地址
            jqdata_abbreviated=row['jqdata_abbreviated']
            exchange_address = stocksys_models.ExchangeAddress.objects.get(
                stock_jqdata_name=jqdata_abbreviated)
            stocksys_models.Fund.objects.create(
                name=row['fund_name'],
                code=row['fund_code'],
                last_update_time=row['last_update_time'],
                start_date=row['start_date'].to_pydatetime(),
                end_date=row['end_date'].to_pydatetime(),
                type=row['type'],
                exchange_address=exchange_address,
                abbreviated_name=row['abbreviated_name']
            )
        self.stdout.write(self.style.SUCCESS('结束载入'))
